package com.pan.download5.factory.builder;

import com.pan.crawler.Directory;
import com.pan.crawler.Page;
import com.pan.download5.config.entity.LineInfo;
import com.pan.download5.factory.DirectoryFactory;
import com.pan.download5.factory.PageFactory;
import com.pan.download5.factory.impl.CommonDirectoryFactory;
import com.pan.download5.factory.impl.CommonPageFactory;

import java.util.Map;

public class CommonAbstractFactory extends AbstractPageDirectoryFactory{
    private String directoryName = "directory";
    private String pageName = "page";




    private DirectoryFactory createDirectoryFactory(LineInfo lineInfo) {
        Map<String, String> infoMap = lineInfo.getInfoMap();
        String directoryClassName = super.getMapValue(infoMap, directoryName);
        try {
            Class<? extends Directory> directoryClass = (Class<? extends Directory>) Class.forName(directoryClassName);
            DirectoryFactory directoryFactory = new CommonDirectoryFactory(directoryClass);
            return directoryFactory;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }


    private PageFactory createPageFactory(LineInfo lineInfo) {
        Map<String, String> infoMap = lineInfo.getInfoMap();
        String pageClassName = super.getMapValue(infoMap, pageName);
        try {
            Class<? extends Page> pageClass = (Class<? extends Page>) Class.forName(pageClassName);
            PageFactory pageFactory = new CommonPageFactory(pageClass);
            return pageFactory;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public FactoryEntity createFactory(LineInfo lineInfo) {
        DirectoryFactory directoryFactory = this.createDirectoryFactory(lineInfo);
        PageFactory pageFactory = this.createPageFactory(lineInfo);
        return new FactoryEntity(directoryFactory, pageFactory);
    }
}
